package com.qf.controller;

import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.StringUtils;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "RegistServlet",urlPatterns = "/registservlet")
public class RegistServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1接收数据
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        request.setAttribute("username", username);
        request.setAttribute("password", password);
        //2校验
        if(StringUtils.isEmpty(username)){
            request.setAttribute("msg","用户名不能为空" );
            request.getRequestDispatcher("/regist.jsp").forward(request, response);
            return;
        }
        if(StringUtils.isEmpty(password)){
            request.setAttribute("msg","密码不能为空" );
            request.getRequestDispatcher("/regist.jsp").forward(request, response);
            return;
        }

        //3 创建业务对象
        UserService userService=new UserServiceImpl();
        User user=new User(0, username,password,1);
        try {
            userService.regit(user);
            request.setAttribute("msg","注册成功" );
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","注册失败:"+e.getMessage());
        }
        request.getRequestDispatcher("/index.jsp").forward(request, response);

    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
